package com.xiaoyi.utils;

import com.alibaba.fastjson.JSONObject;
import com.xiaoyi.bean.ProxyInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ProxyCralwerUnusedVPN {
    ThreadLocal<Integer> localWantedNumber = new ThreadLocal<Integer>();
    ThreadLocal<List<ProxyInfo>> localProxyInfos = new ThreadLocal<List<ProxyInfo>>();

    public static void main(String[] args) {
        ProxyCralwerUnusedVPN proxyCrawler = new ProxyCralwerUnusedVPN();
        /**
         * 想要获取的代理IP个数，由需求方自行指定。（如果个数太多，将导致返回变慢）
         */
        proxyCrawler.startCrawler(1);

    }

    /**
     * 暴露给外部模块调用的入口
     * @param wantedNumber 调用方期望获取到的代理IP个数
     */
    public void startCrawler(int wantedNumber) {

        kuaidailiCom("http://www.xicidaili.com/nn/", wantedNumber);
        kuaidailiCom("http://www.xicidaili.com/nt/", wantedNumber);
        kuaidailiCom("http://www.xicidaili.com/wt/", wantedNumber);
        kuaidailiCom("http://www.kuaidaili.com/free/inha/", wantedNumber);
        kuaidailiCom("http://www.kuaidaili.com/free/intr/", wantedNumber);

    }//https://www.kuaidaili.com/free/inha/2/

    private void kuaidailiCom(String baseUrl, int totalPage) {
        String ipReg = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3} \\d{1,6}";
        Pattern ipPtn = Pattern.compile(ipReg);
        totalPage = totalPage+1;
        for (int i = 1; i < totalPage; i++) {
            try {
                Document doc = Jsoup.connect(baseUrl + i + "/")
                        .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                        .header("Accept-Encoding", "gzip, deflate, sdch")
                        .header("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6")
                        .header("Cache-Control", "max-age=0")
                        .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36")
                        .header("Cookie", "Hm_lvt_7ed65b1cc4b810e9fd37959c9bb51b31=1462812244; _gat=1; _ga=GA1.2.1061361785.1462812244")
                        .header("Host", "www.kuaidaili.com")
                        .header("Referer", "http://www.kuaidaili.com/free/outha/")
                        .timeout(30 * 1000)
                        .get();
                Matcher m = ipPtn.matcher(doc.text());
                while (m.find()) {
                    String[] strs = m.group().split(" ");
                    if (checkProxy(strs[0], Integer.parseInt(strs[1]))) {
                        System.out.println("获取到可用代理IP\t" + strs[0] + "\t" + strs[1]);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("protocol","http");
                        jsonObject.put("ip",strs[0]);
                        jsonObject.put("port",strs[1]);
                        String prox = jsonObject.toJSONString()+"\n";
                        FileUtilsCompat.wirteStr2File(prox,FileUtilsCompat.ROOT_PATH + File.separator + "proxis.log",true);
//                        addProxy(strs[0], strs[1], "http");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static boolean checkProxy(String ip, Integer port) {
        System.out.println("------测试----->"+ip+":"+port);
        try {
            //http://1212.ip138.com/ic.asp 可以换成任何比较快的网页
            Document document = Jsoup.connect("https://www.baidu.com")
                    .timeout(2 * 1000)
                    .proxy(ip, port)
                    .get();

            return true;
        } catch (Exception e) {
            return false;
        }
    }



}
